package com.seo.controller.lightpay;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.seo.pojo.ReturnBody;
import com.seo.service.lightpay.impl.LightPayAlipayServiceImpl;
import com.seo.utils.CommonUtil;
import com.seo.utils.alipay.AlipayConfig;
import com.seo.utils.alipay.AlipayUtil;
import com.seo.utils.alipay.LightPayCashierAlipay;

import lombok.extern.slf4j.Slf4j;

/**
 * 支付回调Controller <br/>
 * 
 * @author shibeilei
 * @version 2017.11.30 12:20
 */
@Slf4j
@Controller
@RequestMapping(value = "/lightpay/notify/")
public class LightPayNotifyController {

	@Autowired
	private AlipayUtil alipayUtil;

	@Autowired
	private LightPayAlipayServiceImpl lightPayAlipayServiceImpl;

	/**
	 * 支付宝回调 <br/>
	 * 
	 * @param request  request
	 * @param response response
	 * @author shibeilei
	 * @version 2017.11.30 11:40
	 */
	@RequestMapping(value = "alipay/{payType}/{userId}")
	public void alipay(@PathVariable("payType") String payType, @PathVariable("userId") Integer userId,
			HttpServletRequest request, HttpServletResponse response) {
		String tradeId = CommonUtil.getUUID();
		log.info("[{}]-【支付宝回调】-【开始】", tradeId);
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e1) {
			log.error("[{}]-【支付宝回调】-【异常】", tradeId);
			e1.printStackTrace();
		}
		log.info("[{}]-【支付宝回调】-【校验参数】", tradeId);
		if (!LightPayCashierAlipay.AlipayType.isExists(payType)) {
			log.error("[{}]-【支付宝回调】-【支付类型不存在】", tradeId);
			out.write("fail");
		}
		if (userId == null || userId < 0) {
			log.error("[{}]-【支付宝回调】-【用户ID不能为空】", tradeId);
			out.write("fail");
		}

		Map<String,String> params = new HashMap<String,String>();

		try {
			
			Map<String,String[]> requestParams = request.getParameterMap();
			for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
				String name = (String) iter.next();
				String[] values = (String[]) requestParams.get(name);
				String valueStr = "";
				for (int i = 0; i < values.length; i++) {
					valueStr = (i == values.length - 1) ? valueStr + values[i]
							: valueStr + values[i] + ",";
				}
				//乱码解决，这段代码在出现乱码时使用
				//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
				params.put(name, valueStr);
			}
			log.info("[{}]-【支付宝回调】-【验证参数】", tradeId);
			AlipayConfig ac = lightPayAlipayServiceImpl.getAlipayConfig(payType, userId);
			if (ac == null) {
				log.error("[{}]-【支付宝回调】-【支付宝配置不存在】", tradeId);
				out.write("fail");
			}
			LightPayCashierAlipay result = alipayUtil.getNotifyResult(params, ac);
			log.info("[{}]-【支付宝回调】-【调用收银服务】", tradeId);
			result.setAc(ac);
			ReturnBody rb = lightPayAlipayServiceImpl.updateLightPayCashier(tradeId, result);
			if (rb.isSuccess()) {
				log.info("[{}]-【支付宝回调】-【成功】", tradeId);
				out.write("success");
			} else {
				log.error("[{}]-【支付宝回调】-【异常】-【返回：fail】", tradeId);
				out.write("fail");
			}

		} catch (Exception e) {
			log.error("[{}]-【支付宝回调】-【返回：fail】-【异常-[{}]】", tradeId, e);
			out.write("fail");
		}
		log.info("[{}]-【支付宝回调】-【结束】", tradeId);

	}

}
